package com.xgkj.diyiketang.yizhibo;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easyvaas.sdk.live.base.interactive.OnInteractiveLiveListener;
import com.easyvaas.sdk.live.wrapper.EVLive;
import com.easyvaas.sdk.player.EVPlayer;
import com.easyvaas.sdk.player.PlayerConstants;
import com.easyvaas.sdk.player.base.EVPlayerBase;
import com.easyvaas.sdk.player.base.EVPlayerParameter;
import com.easyvaas.sdk.player.base.EVVideoView;

import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xgkj.diyiketang.EatShowApp;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.BaseActivity;
import com.xgkj.diyiketang.activity.GuoxueBuyVIPActivity;
import com.xgkj.diyiketang.activity.HisDetailActivity;
import com.xgkj.diyiketang.activity.JuBaoActivity;
import com.xgkj.diyiketang.activity.LiveOverActivity;
import com.xgkj.diyiketang.activity.MyFlowerActivity;
import com.xgkj.diyiketang.activity.MyGoldCoinActivity;
import com.xgkj.diyiketang.activity.WbcallbackActivity;
import com.xgkj.diyiketang.activity.ZhuanyunMoneyActivity;
import com.xgkj.diyiketang.activity.data.AudieceAdapter;
import com.xgkj.diyiketang.activity.data.LiveLiuYanAdapter;
import com.xgkj.diyiketang.data.AudieceInfo;
import com.xgkj.diyiketang.data.DynamicInfo;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.data.GifInfo;
import com.xgkj.diyiketang.data.LiveParentInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.liwudianzan.HeartEvaluator;
import com.xgkj.diyiketang.liwudianzan.HeartImageView;
import com.xgkj.diyiketang.task.AddOrCancleFocusTask;
import com.xgkj.diyiketang.task.GetFlowerBalanceTask;
import com.xgkj.diyiketang.task.GetUsemingeTask;
import com.xgkj.diyiketang.task.GetUserDetailTask;
import com.xgkj.diyiketang.task.LiveCommentTask;
import com.xgkj.diyiketang.task.LiveDetailTask;
import com.xgkj.diyiketang.task.LiveDynamicTask;
import com.xgkj.diyiketang.task.SongLiwuTask;
import com.xgkj.diyiketang.task.ZhiboActionTask;
import com.xgkj.diyiketang.util.AccessTokenKeeper;
import com.xgkj.diyiketang.util.DialogUtil;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.LogUtils;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.util.WeixinShareUtil;
import com.xgkj.diyiketang.weidget.GifView;
import com.xgkj.diyiketang.weidget.HorizontalGridView;
import com.xgkj.diyiketang.weidget.MediaController;
import com.xgkj.diyiketang.weidget.RoundImageView;
import com.xgkj.diyiketang.yizhibo.been.PlayOption;
import com.xgkj.eatshow.wxapi.WXEntryActivity;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.SoftReference;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;
import tv.danmaku.ijk.media.player.IMediaPlayer;

public class PlayerNewActivity extends BaseActivity implements IWeiboHandler.Response, View.OnClickListener, LiveLiuYanAdapter.LiwuListener
        , MediaController.OnUseGuankanquanListener {

    private static final int REQUEST_CODE_REGISTER = 1;
    private Dialog mLoadingDialog;

    //private View mWatchOptView;

    private String mVid = "";

    private int getAnchorTaskId = -1;
    private int getDynamicListTaskId = -1;
    private ImageView mZhuBoImg;
    private TextView mZhuBoNick;
    private TextView mGuankanshu;
    EatShowUserInfo userinfo;
    HorizontalGridView mAudieGridList;
    private List<DynamicInfo> dynamicList;
    private List<AudieceInfo> audienceList;
    private AudieceAdapter adapter;
    private ListView lyListView;
    private LiveLiuYanAdapter lyAdapter;
    private ImageView huifuBtn;
    private LinearLayout huifuLayout;
    private EditText mPingLunEdit;
    private Button mPingLunBtn;
    private String cmtText;
    private int cmtTaskId = -1;
    //    private Timer timer;
    private MyHandler mHandler;
    private ImageView mShareImg;
    private PopupWindow boPopWindow;
    private RoundImageView mLiveZhuBoImg;
    private TextView mLiveZhuBoNick;
    private TextView mLiveZhuBoSign;
    private String curtime;
    private String dynamciTime;
    private Button guanzhuBtn;
    private int addFocusTaskId = -1;
    private String targetId;
    private ImageView mCloseView;
    private Context mContext;
    private PopupWindow popWindow;
    private String share_path;

    private WeixinShareReceive mWeixinShareReceive;
    private String weixinsharetype;
    private String weixinuseropenid;
    private String weibouserid;
    private Bitmap weiboShareBitmap;
    private byte[] weixinshareByte;
    private IWXAPI api;
    private IWeiboShareAPI mWeiboShareAPI = null;
    private String shoucangtype;
    public static Tencent mTencent;
    private String share_title;
    private RelativeLayout mAllLayout;
    private String guankanNum;
    private ViewPager viewPager;
    private ArrayList<EatShowUserInfo> mList = new ArrayList<>();
    private int currentPosition;
    private ImageView liveLiwu;
    //    private ImageView liveZan;
    private PopupWindow liwuPopWindow;
    private GifInfo selectGift;
    private int songliwuTaskId = -1;
    private String jinbiBalance;
    //    private GifView liwuImageView;
    private GifImageView liwuImageView;
    private LinearLayout liwuLayout;
    private int lianjicount = 0;
    private long currentTime = 0;
    private long beforeTime = 0;
    private LinearLayout liwuTanKuang;
    private RelativeLayout dianzanLayout;
    private int goldCoinTaskId = -1;
    private int doShareTaskId = -1;
    private InputMethodManager in;
    private MediaController mMediaController;
    private Button zhiboDescBtn;
    private PopupWindow descPopWindow;
    private TextView desc_title;
    private TextView desc_content;

    private EVVideoView mVideoView;
    private EVPlayer mEVPlayer;
    private EVLive mEVLive;
    private PlayOption mPlayOption;
    private PowerManager.WakeLock mWakeLock;
    private final static String TAG = PlayerActivity.class.getSimpleName();
    public static final String EXTRA_PLAY_CONFIG_BEAN = "extra_play_config_bean";
    String uri = "";
    private String liveState = "1";
    private String isUse;
    private String vdid;
    private int detailTaskId = -1;
    private String quotaId;
    private String isMovie;
    private EatShowUserInfo userInfo;
    private String zhuanyun_jihuo;
    private String z_minge;
    private String parent_jihuo;
    private String p_minge;
    private int useMingeTask = -1;
    private String isPlayer;
    public static boolean used_minge;
    private String zhibo_play;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player_new);
        mContext = this;
        mTencent = Tencent.createInstance(ProtocolConst.QQ_ID, this.getApplicationContext());
        api = WXAPIFactory.createWXAPI(mContext, ProtocolConst.APP_ID);
//        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this,
//                ProtocolConst.WEIBO_APP_KEY);//这粒要换
//        mWeiboShareAPI.registerApp();
//        if (savedInstanceState != null) {
//            mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
//        }
        in = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        mHandler = new MyHandler(this);

        if (!TextUtils.isEmpty(getIntent().getStringExtra(Constants.EXTRA_KEY_VIDEO_ID))) {
            mVid = getIntent().getStringExtra(Constants.EXTRA_KEY_VIDEO_ID);
//            share_path = "http://115.28.236.67:8096/classroom/live.htmll?vid=" + mVid + "";
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra(Constants.LIVE_STATE))) {
            liveState = getIntent().getStringExtra(Constants.LIVE_STATE);
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra(Constants.ZHIBO_PLAY))){
            zhibo_play = getIntent().getExtras().getString(Constants.ZHIBO_PLAY);
        }
        initUIComponents();
        initDescPopWindow();
        initBOPopWindow();
        initPopWindow();
        initLiwuPop();
        EVPlayerParameter.Builder builder = new EVPlayerParameter.Builder();
        builder.setLive(true);
        mEVPlayer = new EVPlayer(this);
        mEVPlayer.setParameter(builder.build());
        mEVPlayer.setVideoView(mVideoView);
        mEVPlayer.setOnPreparedListener(mOnPreparedListener);
        mEVPlayer.setOnCompletionListener(mOnCompletionListener);
        mEVPlayer.setOnInfoListener(mOnInfoListener);
        mEVPlayer.setOnErrorListener(mOnErrorListener);
        mEVPlayer.onCreate();

        String type = "";
        if (!TextUtils.isEmpty(getIntent().getExtras().getString("type"))) {
            type = getIntent().getExtras().getString("type");
            if (type.equals("Myzhibo")) {
                if (!TextUtils.isEmpty(getIntent().getSerializableExtra("ZHIBO_LIST").toString())) {
                    mList = (ArrayList<EatShowUserInfo>) getIntent().getSerializableExtra("ZHIBO_LIST");
                    currentPosition = getIntent().getIntExtra("CURRENT_POSITION", 0);
                }
            } else if (type.equals("liveFirst")) {
            } else if (type.equals("pwd")) {
            } else if (type.equals("goumai")) {
            }
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra("videoid")))
            vdid = getIntent().getStringExtra("videoid");
        if (!TextUtils.isEmpty(getIntent().getStringExtra("isMovie")))
            isMovie = getIntent().getStringExtra("isMovie");
        if (!TextUtils.isEmpty(getIntent().getStringExtra("isPlayer"))) {
            zhibo_play = getIntent().getStringExtra("isPlayer");
        }
        initListeners();
        startPlay();

    }

    private EVPlayerBase.OnPreparedListener mOnPreparedListener = new EVPlayerBase.OnPreparedListener() {
        @Override
        public boolean onPrepared() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    acquireWakeLock();
                    dismissLoadingDialog();
                }
            });
            return true;
        }
    };

    private void initListeners() {
        findViewById(R.id.guanbi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mEVPlayer) {
                    mEVPlayer.watchStop();
                }
                finish();
            }
        });
    }

    private void startPlay() {
        if (TextUtils.isEmpty(mVid)) {
            share_path = "http://115.28.236.67:8096/classroom/live.html?vid=" + mVid + "";
        }

        if (liveState.equals("0")) {
            mEVPlayer.watchStart(mVid, true);
        } else if (liveState.equals("1")) {
            mEVPlayer.watchStart(mVid, false);
        }
        doGetData();
    }

    private EVPlayerBase.OnCompletionListener mOnCompletionListener = new EVPlayerBase.OnCompletionListener() {
        @Override
        public boolean onCompletion() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Utils.getOneButtonDialog(PlayerNewActivity.this,
                            getString(R.string.msg_play_complete), false, false,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    finish();
                                    releaseWakeLock();
                                }
                            }).show();
                    if (null != mEVPlayer) {
                        mEVPlayer.watchStop();
                    }
                }
            });
            return true;
        }
    };

    private void initUIComponents() {
//        mVideoView = (YZBVideoView) findViewById(R.id.player_surface_view);
        Intent intent = getIntent();
        if (!TextUtils.isEmpty(intent.getStringExtra("isUse")) && !TextUtils.isEmpty(zhibo_play)) {
            isUse = intent.getStringExtra("isUse");
            mMediaController = new MediaController(this, isUse, zhibo_play);
        } else {
            mMediaController = new MediaController(this);
        }
        mVideoView = (EVVideoView) findViewById(R.id.player_surface_view);
//        mMediaController = new MediaController(this);
        mMediaController.setMediaPlayer(mediaControl);
        mMediaController.setAnchorView(mVideoView, "play");
        mMediaController.setOnUseGuankanquanListener(this);
        liwuImageView = (GifImageView) findViewById(R.id.liwu_imageview);
        dianzanLayout = (RelativeLayout) findViewById(R.id.dianzan_layout);
        mAllLayout = (RelativeLayout) findViewById(R.id.all_Layout);
        mZhuBoImg = (ImageView) findViewById(R.id.zhubo_img);
        mZhuBoImg.setOnClickListener(this);
        mZhuBoNick = (TextView) findViewById(R.id.zhubo_nick);
        mGuankanshu = (TextView) findViewById(R.id.guankanshu);
        mAudieGridList = (HorizontalGridView) findViewById(R.id.audie_list);
        adapter = new AudieceAdapter(this);
        mAudieGridList.setAdapter(adapter);
        setValue();
        lyListView = (ListView) findViewById(R.id.liuyan_list);
        lyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                zanDonghua();
                if (huifuLayout.getVisibility() == View.VISIBLE) {
                    huifuLayout.setVisibility(View.GONE);
                    huifuBtn.setVisibility(View.VISIBLE);
                    mShareImg.setVisibility(View.VISIBLE);
                    liveLiwu.setVisibility(View.VISIBLE);
//                    liveZan.setVisibility(View.VISIBLE);
                    try {
                        in.hideSoftInputFromWindow(PlayerNewActivity.this.getCurrentFocus().getWindowToken(), 0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                if (liwuLayout.getVisibility() == View.VISIBLE) {
                    liwuLayout.setVisibility(View.GONE);
                }
            }
        });
        lyAdapter = new LiveLiuYanAdapter(mContext);
        lyAdapter.setLiwuListener(this);
        lyListView.setAdapter(lyAdapter);
        huifuBtn = (ImageView) findViewById(R.id.live_huifu);
        huifuBtn.setOnClickListener(this);
        huifuLayout = (LinearLayout) findViewById(R.id.huifu_layout);
        mPingLunEdit = (EditText) findViewById(R.id.pinglun);
        mPingLunBtn = (Button) findViewById(R.id.fabiaopinglun);
        mPingLunBtn.setOnClickListener(this);
        mShareImg = (ImageView) findViewById(R.id.live_share);
        mShareImg.setOnClickListener(this);
        guanzhuBtn = (Button) findViewById(R.id.guanzhu_btn);
        guanzhuBtn.setOnClickListener(this);
        mCloseView = (ImageView) findViewById(R.id.guanbi);
        mCloseView.setOnClickListener(this);
        liveLiwu = (ImageView) findViewById(R.id.live_liwu);
//        liveZan = (ImageView) findViewById(R.id.live_zan);
        liveLiwu.setOnClickListener(this);
//        liveZan.setOnClickListener(this);
        liwuTanKuang = (LinearLayout) findViewById(R.id.liwutankuang);
        mAllLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (huifuLayout.getVisibility() == View.VISIBLE) {
                    huifuLayout.setVisibility(View.GONE);
                    huifuBtn.setVisibility(View.VISIBLE);
                    mShareImg.setVisibility(View.VISIBLE);
                    liveLiwu.setVisibility(View.VISIBLE);
//                    liveZan.setVisibility(View.VISIBLE);
                }

                if (liwuLayout.getVisibility() == View.VISIBLE) {
                    liwuLayout.setVisibility(View.GONE);
                }

                if (!isLive) {
                    if (mMediaController.isShowing()) {
                        mMediaController.hide();
                        mShareImg.setVisibility(View.VISIBLE);
                        liveLiwu.setVisibility(View.VISIBLE);
                    } else {
                        mMediaController.show();
                        mShareImg.setVisibility(View.GONE);
                        liveLiwu.setVisibility(View.GONE);
                    }
                }

            }
        });

        zhiboDescBtn = (Button) findViewById(R.id.zhibo_desc);
        zhiboDescBtn.setOnClickListener(this);

        getUserDetail();
        getGoldBalance(null);
    }

    private boolean isCreate = false;

    private void play(EatShowUserInfo info, int i) {
        View v = viewPager.findViewWithTag(i);
        View next_v = viewPager.findViewWithTag(i + 1);
        View prev_v = viewPager.findViewWithTag(i - 1);
        mVid = info.getVid();
        PalLog.e("易直播vid", mVid);
        if (v != null) {
            ImageView imageView = (ImageView) v.findViewById(R.id.fengmian);
            if (imageView != null) {
                imageView.setVisibility(View.GONE);
            }
            mVideoView = (EVVideoView) v.findViewById(R.id.player_surface_view);
            if (mVideoView != null) {
                mVideoView.setOnClickListener(this);
                mVideoView.setVisibility(View.VISIBLE);
            }
        }

        if (next_v != null) {
            ImageView imageView = (ImageView) v.findViewById(R.id.fengmian);
            if (imageView != null) {
                imageView.setVisibility(View.VISIBLE);
            }
            EVVideoView videoView = (EVVideoView) v.findViewById(R.id.player_surface_view);
            if (videoView != null) {
                videoView.setVisibility(View.GONE);
            }
        }
        if (prev_v != null) {
            ImageView imageView = (ImageView) v.findViewById(R.id.fengmian);
            if (imageView != null) {
                imageView.setVisibility(View.VISIBLE);
            }
            EVVideoView videoView = (EVVideoView) v.findViewById(R.id.player_surface_view);
            if (videoView != null) {
                videoView.setVisibility(View.GONE);
            }
        }
        isCreate = true;
//        share_path = "http://app.sjmingze.com/yzb/yzb.html?vid=" + mVid + "";


        //获取用户登陆的session信息。未登录用户session为空，也可以观看
        if (!isFinishing()) {
            showLoadingDialog(R.string.loading_data, true, true);
        }
    }

    private EVPlayerBase.OnErrorListener mOnErrorListener = new EVPlayerBase.OnErrorListener() {
        @Override
        public boolean onError(int what, int extra) {
            switch (what) {
                case PlayerConstants.EV_PLAYER_ERROR_SDK_INIT:
//                    showToastOnUiThread(R.string.msg_sdk_init_error);
                    Toast.makeText(PlayerNewActivity.this, "sdk初始化失败", Toast.LENGTH_SHORT).show();
                    break;
                case PlayerConstants.EV_PLAYER_ERROR_GET_RESOURCE:
                    Toast.makeText(PlayerNewActivity.this, "请求播放调度出错，播放失败", Toast.LENGTH_SHORT).show();
//                    showToastOnUiThread(R.string.msg_live_show_error);
                    break;
                case PlayerConstants.EV_PLAYER_ERROR_GET_URL:
                    Toast.makeText(PlayerNewActivity.this, "获取视频地址失败，播放失败", Toast.LENGTH_SHORT).show();

//                    showToastOnUiThread(R.string.msg_live_redirect_error);
                    break;
                default:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Utils.getOneButtonDialog(PlayerNewActivity.this,
                                    getString(R.string.msg_play_error), false, false,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                            dismissLoadingDialog();
                                            releaseWakeLock();
                                            if (null != mEVPlayer) {
                                                mEVPlayer.onStop();
                                            }
                                            finish();
                                        }
                                    }).show();
                        }
                    });
                    break;
            }

            return true;
        }
    };

    private void showToastOnUiThread(final int resId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isFinishing()) {
                    return;
                }

//                SingleToast.show(getApplicationContext(), resId);
                finish();
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (null != mEVPlayer) {
            mEVPlayer.onStart();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        doFresh();
        if (null != mEVPlayer) {
            mEVPlayer.onResume();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (null != mEVPlayer) {
            mEVPlayer.onStop();
//            timer.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMediaController != null && mMediaController.isShowing()) {
            mMediaController.hide();
            mShareImg.setVisibility(View.VISIBLE);
            liveLiwu.setVisibility(View.VISIBLE);
        }
        if (null != mEVPlayer) {
            mEVPlayer.onDestroy();
        }

        liwuLayout.setVisibility(View.GONE);
        if (errorDialog != null && errorDialog.isShowing()) {
            errorDialog.dismiss();
        }
        mHandler.removeMessages(111);
        dismissLoadingDialog();
        releaseWakeLock();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mEVPlayer != null) {
            mEVPlayer.onPause();
        }
        mHandler.removeMessages(111);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_player, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQUEST_CODE_REGISTER:
                if (null != data) {
                    String vid = data.getStringExtra(Constants.EXTRA_KEY_VIDEO_ID);
                    if (!TextUtils.isEmpty(vid)) {
                        if (null != mEVPlayer) {
                            mEVPlayer.setOnInfoListener(mOnInfoListener);
                            mEVPlayer.setOnErrorListener(mOnErrorListener);
//                            uri = "liveshow?lid=" + vid + "&support=" + PlayerConstants.LIVE_RTMP_PULLE +
//                                    "&proto=" + PlayerConstants.HTTP200JSONE;
                            if (liveState.equals("0")) {
                                mEVPlayer.watchStart(mVid, true);
                            } else if (liveState.equals("1")) {
                                mEVPlayer.watchStart(mVid, false);
                            }
                        }
                        if (!isFinishing()) {
                            showLoadingDialog(R.string.loading_data, true, true);
                        }
                    }
                }
                break;
        }
    }

    private EVPlayerBase.OnInfoListener mOnInfoListener = new EVPlayerBase.OnInfoListener() {
        @Override
        public boolean onInfo(int what, int extra) {
            switch (what) {
                case IMediaPlayer.MEDIA_INFO_BUFFERING_START:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!isFinishing()) {
                                showLoadingDialog(R.string.loading_data, true, true);
                            }
                        }
                    });
                    break;
                case IMediaPlayer.MEDIA_INFO_BUFFERING_END:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissLoadingDialog();
                        }
                    });
                    break;
            }
            return true;
        }
    };
    private OnInteractiveLiveListener mOnInteractiveLiveListener = new OnInteractiveLiveListener() {
        @Override
        public void onJoinChannelResult(boolean isSuccess) {

        }

        @Override
        public void onLeaveChannelSuccess() {
            onInteractiveEnd();
        }

        @Override
        public void onFirstRemoteVideoDecoded() {
            onInteractiveStart();
        }

        @Override
        public void onFirstLocalVideoFrame() {

        }

        @Override
        public void onUserOffline(int userId, int reason) {
            onInteractiveEnd();
        }

        @Override
        public void onError(int code, String message) {
        }
    };

    private void onInteractiveStart() {
        mEVPlayer.onDestroy();
        mVideoView.setVisibility(View.INVISIBLE);
    }

    private void onInteractiveEnd() {
        mVideoView.setVisibility(View.VISIBLE);
        mEVPlayer.onCreate();
        startPlay();

        if (!isFinishing()) {
            showLoadingDialog(R.string.loading_data, true, true);
        }
    }

    private MediaController.MediaPlayerControl mediaControl = new MediaController.MediaPlayerControl() {
        @Override
        public void start() {
            if (mVideoView != null) {
                mVideoView.start();
            }
        }

//        @Override
//        public boolean useGuankanquan() {
//            return mVideoView != null && mVideoView.useGuankanquan();
//        }

        @Override
        public void pause() {
            if (mVideoView != null) {
                mVideoView.pause();
            }
        }

//        @Override
//        public int getDuration() {
//            return 0;
//        }
//
//        @Override
//        public int getCurrentPosition() {
//            return 0;
//        }

        @Override
        public int getDuration() {
//            if (mVideoView != null&&mVideoView.getDuration())
            return mVideoView != null ? (int) mVideoView.getDuration() : 0;
        }

        @Override
        public int getCurrentPosition() {
            return mVideoView != null ? (int) mVideoView.getCurrentPosition() : 0;

        }

        @Override
        public void seekTo(long pos) {
            if (mVideoView != null) {
                mVideoView.seekTo((int) pos);
            }
        }

        @Override
        public boolean isPlaying() {
            return mVideoView != null && mVideoView.isPlaying();
        }

        @Override
        public int getBufferPercentage() {
            return mVideoView != null ? mVideoView.getBufferPercentage() : 0;
        }

        @Override
        public boolean canPause() {
            return mVideoView != null && mVideoView.canPause();
        }

        @Override
        public boolean canSeekBackward() {
            return true;
        }

        @Override
        public boolean canSeekForward() {
            return true;
        }
    };
    private boolean isZhuboBalance = false;

    private void getGoldBalance(String userId) {
        GetFlowerBalanceTask goldCoinTask = new GetFlowerBalanceTask(userId);
        goldCoinTask.addListener(new MyListener(this));
        if (ViewUtil.isNull(userId)) {
            //个人的
            isZhuboBalance = false;
        } else {
            //主播的
            isZhuboBalance = true;
        }
        goldCoinTaskId = getEatShowApp().getTaskManager().addTask(goldCoinTask);
    }

    private void initBOPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.pop_live_anchor, null);
        view.findViewById(R.id.livejubao).setOnClickListener(this);
        view.findViewById(R.id.liveclose).setOnClickListener(this);
        mLiveZhuBoImg = (RoundImageView) view.findViewById(R.id.zhubo_img);
        mLiveZhuBoImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, HisDetailActivity.class);
                intent.putExtra("USERID", targetId);
                startActivity(intent);
            }
        });
        mLiveZhuBoNick = (TextView) view.findViewById(R.id.zhubo_nick);
        mLiveZhuBoSign = (TextView) view.findViewById(R.id.zhubo_sign);
        mLivezhuboBalance = (TextView) view.findViewById(R.id.zhubo_balance);

        boPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        boPopWindow.setBackgroundDrawable(new ColorDrawable());
        boPopWindow.setFocusable(true);
        boPopWindow.setOutsideTouchable(true);
    }


    private void initDescPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.pop_desc, null);
        view.findViewById(R.id.i_know).setOnClickListener(this);
        desc_title = (TextView) view.findViewById(R.id.title);
        desc_content = (TextView) view.findViewById(R.id.desc);
        descPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        descPopWindow.setBackgroundDrawable(new ColorDrawable());
        descPopWindow.setFocusable(true);
        descPopWindow.setOutsideTouchable(true);
    }


    private void setValue() {
        int count = adapter.getCount();
        int width = count * ViewUtil.dip2px(mContext, 32) + (count - 1) * ViewUtil.dip2px(mContext, 10);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width,
                ViewUtil.dip2px(mContext, 40));
        mAudieGridList.setLayoutParams(params);
        mAudieGridList.setColumnWidth(ViewUtil.dip2px(mContext, 32));
        mAudieGridList.setStretchMode(GridView.NO_STRETCH);
        mAudieGridList.setNumColumns(count);
    }

    private void acquireWakeLock() {
        if (null == mWakeLock) {
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG);
        }

        if (!mWakeLock.isHeld()) {
            mWakeLock.acquire();
        }
    }

    private void releaseWakeLock() {
        if (null != mWakeLock) {
            mWakeLock.release();
            mWakeLock = null;
        }
    }

    private void showLoadingDialog(int resId, boolean dismissTouchOutside, boolean cancelable) {
        showLoadingDialog(getString(resId), dismissTouchOutside, cancelable);
    }

    private void showLoadingDialog(String message, boolean dismissTouchOutside, boolean cancelable) {
        if (mLoadingDialog == null) {
            mLoadingDialog = Utils.getProcessDialog(this, message, dismissTouchOutside, cancelable);
        }
        mLoadingDialog.setCancelable(cancelable);
        mLoadingDialog.setCanceledOnTouchOutside(dismissTouchOutside);
        mLoadingDialog.show();
    }

    private void dismissLoadingDialog() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.live_huifu:
                huifuLayout.setVisibility(View.VISIBLE);
                huifuBtn.setVisibility(View.GONE);
                mShareImg.setVisibility(View.GONE);
                liveLiwu.setVisibility(View.GONE);
//                liveZan.setVisibility(View.GONE);
                break;
            case R.id.fabiaopinglun:
                huifuLayout.setVisibility(View.GONE);
                huifuBtn.setVisibility(View.VISIBLE);
                mShareImg.setVisibility(View.VISIBLE);
                liveLiwu.setVisibility(View.VISIBLE);
//                liveZan.setVisibility(View.VISIBLE);
                try {
                    in.hideSoftInputFromWindow(PlayerNewActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (checkInput()) {
                    publishComment();
                    mPingLunEdit.setText(null);
                }
                break;
            case R.id.zhibo_desc:
                descPopWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
                break;
            case R.id.i_know:
                descPopWindow.dismiss();
                break;
            case R.id.zhubo_img:
                if (targetId == null) return;
                getGoldBalance(targetId);
                boPopWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
                break;
            case R.id.guanzhu_btn:
                //ToastUtil.showMessage(mContext,"dfsafdas");
                AddOrCancleFocusTask task = new AddOrCancleFocusTask(targetId, "0");
                task.addListener(new MyListener(this));
                addFocusTaskId = getEatShowApp().getTaskManager().addTask(task);
                break;
            case R.id.liveclose:
                boPopWindow.dismiss();
                break;
            case R.id.livejubao:
                Intent jInent = new Intent(mContext, JuBaoActivity.class);
                startActivity(jInent);
                break;
            case R.id.guanbi:
                finish();
                break;
            case R.id.live_share:
                popWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                break;

            case R.id.share_to_timeline:
                weixinsharetype = "sharefriends";
                shareToWeiXin(share_path, true);
                popWindow.dismiss();
                break;
            case R.id.share_to_weixinfriend:
                weixinsharetype = "sharefriend";
                shareToWeiXin(share_path, false);
                popWindow.dismiss();
                break;
            case R.id.share_to_weibo:
                shareToWeiBo(share_path);
                popWindow.dismiss();
                break;
            case R.id.share_to_qq:
                final Bundle params = new Bundle();
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                params.putString(QQShare.SHARE_TO_QQ_TITLE, "第一课堂");
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY, share_title);
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, share_path);
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "http://www.chiboker.com/diyiketangImage/diyiketang_icon.png");
                // params.putByteArray(QQShare.SHARE_TO_QQ_IMAGE_URL,weixinshareByte);
                params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "第一课堂");
                mTencent.shareToQQ(this, params, qqShareListener);
                popWindow.dismiss();
                break;
            case R.id.live_zan:
//                zanDonghua();
                break;
            case R.id.live_liwu:
//                liwuPopWindow.showAtLocation(v,Gravity.BOTTOM,0,0);
                liwuLayout.setVisibility(View.VISIBLE);
                break;
            case R.id.send_gift_btn:
                if (selectGift != null) {
                    currentTime = System.currentTimeMillis();
                    if (beforeTime == 0) {
                        beforeTime = currentTime;
                    } else {
                        if (currentTime - beforeTime > 5000) {
                            lianjicount = 0;
                            beforeTime = 0;
                        } else {
                            lianjicount++;
                            beforeTime = currentTime;
                        }
                    }
                    songLiwu(selectGift);
                }
                break;
            case R.id.jinbi_balance:
                startActivity(new Intent(mContext, MyFlowerActivity.class));
                break;
            case R.id.zhibo_root:
                zanDonghua();
                if (huifuLayout.getVisibility() == View.VISIBLE) {
                    huifuLayout.setVisibility(View.GONE);
                    huifuBtn.setVisibility(View.VISIBLE);
                    mShareImg.setVisibility(View.VISIBLE);
                    liveLiwu.setVisibility(View.VISIBLE);
//                    liveZan.setVisibility(View.VISIBLE);
                    try {
                        in.hideSoftInputFromWindow(PlayerNewActivity.this.getCurrentFocus().getWindowToken(), 0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                if (liwuLayout.getVisibility() == View.VISIBLE) {
                    liwuLayout.setVisibility(View.GONE);
                }

                if (!isLive) {
                    if (mMediaController.isShowing()) {
                        mMediaController.hide();
                        mShareImg.setVisibility(View.VISIBLE);
                        liveLiwu.setVisibility(View.VISIBLE);
                    } else {
                        mMediaController.show();
                        mShareImg.setVisibility(View.GONE);
                        liveLiwu.setVisibility(View.GONE);
                    }
                }
                break;

        }
    }

    private void doGetData() {
        doGetAnchorInfo();
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        curtime = format.format(date);

        dynamciTime = curtime;
//        getDynamicList();
    }

    private void doFirstZhibo() {
        if (mList != null && mList.size() > 0 && currentPosition == 0) {
            play(mList.get(0), 0);
        } else {
//            viewPager.setCurrentItem(currentPosition);
        }
    }


    private void doGetAnchorInfo() {
        LiveDetailTask dtask = new LiveDetailTask(mVid);
        dtask.addListener(new MyListener(this));
        getAnchorTaskId = getEatShowApp().getTaskManager().addTask(dtask);
    }

    private void getDynamicList() {
//        Date date = new Date();
//        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String time = format.format(date);
        if (ViewUtil.isNull(mVid)) {
            return;
        }
        if (getDynamicListTaskId != -1) {
            return;
        }
        if (dynamciTime == null) {
            return;
        }

        if (!isLive) {
            return;
        }
        LiveDynamicTask dyTask = new LiveDynamicTask(mVid, dynamciTime, "20");
        dyTask.addListener(new MyListener(this));
        getDynamicListTaskId = getEatShowApp().getTaskManager().addTask(dyTask);
    }

    private void publishComment() {
        LiveCommentTask cmtTask = new LiveCommentTask(mVid, cmtText);
        cmtTask.addListener(new MyListener(this));
        cmtTaskId = getEatShowApp().getTaskManager().addTask(cmtTask);
    }

    private boolean checkInput() {
        cmtText = mPingLunEdit.getText().toString().trim();
        if (TextUtils.isEmpty(cmtText)) {
            Toast.makeText(mContext, R.string.no_cmt, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }


    private boolean isLive;
    private TextView mLivezhuboBalance;

    @Override
    public void onUseden() {
        useGuankanquan();
    }

    private void useMnge() {
        //使用观看券
        if (vdid == null || quotaId == null) {
            return;
        }
        GetUsemingeTask task = new GetUsemingeTask(quotaId, mVid);
        task.addListener(new MyListener(mContext));
        useMingeTask = getEatShowApp().getTaskManager().addTask(task);
    }

    private void useGuankanquan() {
        if (zhibo_play.equals("1")) {
            Intent intent = new Intent(this, GuoxueBuyVIPActivity.class);
            startActivity(intent);
            finish();
        } else if (zhibo_play.equals("2")) {
            quotaId = "3d9513eb1b674af98de226b315765e3f";
            if (!TextUtils.isEmpty(zhuanyun_jihuo) && !TextUtils.isEmpty(z_minge)) {
                if (Integer.parseInt(zhuanyun_jihuo) > 0 || Integer.parseInt(z_minge) > 0) {
                    useMnge();
                } else {
                    Intent intent = new Intent(this, ZhuanyunMoneyActivity.class);
                    intent.putExtra("type", "zhuanyun");
                    startActivity(intent);
                    finish();
                }
            } else {
                Intent intent = new Intent(this, ZhuanyunMoneyActivity.class);
                intent.putExtra("type", "zhuanyun");
                startActivity(intent);
                finish();
            }

        } else if (zhibo_play.equals("3")) {
            quotaId = "2737f7a418bf41c998728e6a0f9f253d";
            if (!TextUtils.isEmpty(parent_jihuo) && !TextUtils.isEmpty(p_minge)) {
                if (Integer.parseInt(parent_jihuo) > 0 || Integer.parseInt(p_minge) > 0) {
                    useMnge();
                } else {
                    Intent intent = new Intent(this, ZhuanyunMoneyActivity.class);
                    intent.putExtra("type", "parent");
                    startActivity(intent);
                    finish();
                }
            } else {
                Intent intent = new Intent(this, ZhuanyunMoneyActivity.class);
                intent.putExtra("type", "parent");
                startActivity(intent);
                finish();
            }

        }
    }

    private void getUserDetail() {
        GetUserDetailTask task = new GetUserDetailTask();
        task.addListener(new MyListener(mContext));
        detailTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    class MyListener extends ShowToastTaskEventListener {
        public MyListener(Context context) {
            super(context);
        }

        //    private TaskEventListener doLiveListener = new ShowToastTaskEventListener(this) {
        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == detailTaskId) {
                userInfo = (EatShowUserInfo) data;
                if (userInfo.getList() != null && userInfo.getList().size() > 0) {
                    for (int i = 0; i < userInfo.getList().size(); i++) {
                        String xueyuan = userInfo.getList().get(i).xueyuan;
                        //转运
                        if (xueyuan.equals("3d9513eb1b674af98de226b315765e3f")) {
                            zhuanyun_jihuo = userInfo.getList().get(i).jihuoMinge;
                            z_minge = userInfo.getList().get(i).minge;
                            //父母大学
                        } else {
                            parent_jihuo = userInfo.getList().get(i).jihuoMinge;
                            p_minge = userInfo.getList().get(i).minge;
                        }
                    }
                }
            }
            if (useMingeTask == taskId) {
                isUse = "1";
                EatShowApp.getACache().put("use_minge","true");
                EatShowApp.getACache().put(Constants.USE_GUANKANQUAN,"true");
            }
            if (taskId == getAnchorTaskId) {
                userinfo = (EatShowUserInfo) data;
                if (userinfo != null) {
                    LogUtils.i("info_play", userinfo);
                    desc_title.setText(userinfo.getLiveTitle());
                    String liveContent = userinfo.getLiveContent();
                    if (liveContent != null) {
                        try {
                            liveContent = URLDecoder.decode(liveContent, "utf-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }

                    desc_content.setText(liveContent);
                    targetId = userinfo.getUserId();
                    if (targetId == null) {
                        Utils.getOneButtonDialog(PlayerNewActivity.this,
                                getString(R.string.msg_video_not_exist), false, false,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        dismissLoadingDialog();
                                        releaseWakeLock();
                                        if (null != mEVPlayer) {
                                            mEVPlayer.onStop();
                                        }
                                        finish();
                                    }
                                }).show();
                        return;
                    }
                    ImageCache.getInstance(mContext).loadBitmapToView(
                            mZhuBoImg,
                            userinfo.getUserLogo(),
                            new ViewUtil.Size(ViewUtil.dip2px(mContext, 32), ViewUtil.dip2px(
                                    mContext, 32)));
                    if (userinfo.getNickName() != null) {
                        try {
                            mZhuBoNick.setText(URLDecoder.decode(userinfo.getNickName(), "utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }

                    ImageCache.getInstance(mContext).loadBitmapToView(
                            mLiveZhuBoImg,
                            userinfo.getUserLogo(),
                            new ViewUtil.Size(ViewUtil.dip2px(mContext, 60), ViewUtil.dip2px(
                                    mContext, 60)));
                    if (userinfo.getNickName() != null) {
                        try {
                            mLiveZhuBoNick.setText(URLDecoder.decode(userinfo.getNickName(), "utf-8"));
                            share_title = URLDecoder.decode(userinfo.getNickName(), "utf-8") + "正在第一课堂直播，赶快点开吧！";
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        mLiveZhuBoSign.setText("粉丝数:" + userinfo.getFansNum());
                    }

                    boolean isfoucus = userinfo.isFocus();
                    if (!isfoucus) {
//                        guanzhuBtn.setText("已关注");
                        guanzhuBtn.setVisibility(View.GONE);
                    } else {
//                        guanzhuBtn.setText("关注");
                        guanzhuBtn.setVisibility(View.VISIBLE);
                    }

                    mGuankanshu.setText(userinfo.getViewCount() + "人");
                    guankanNum = userinfo.getViewCount();

                    String state = userinfo.getLiveState();

                    if (state.equals("1")) {
                        liveLiwu.setVisibility(View.VISIBLE);
                        huifuBtn.setVisibility(View.GONE);
                        isLive = false;
                    } else if (state.equals("0")) {
                        liveLiwu.setVisibility(View.VISIBLE);
                        huifuBtn.setVisibility(View.VISIBLE);
//                        liveLiwu.setVisibility(View.GONE);
//                        huifuBtn.setVisibility(View.VISIBLE);
                        isLive = true;
                    }
                }
            } else if (taskId == getDynamicListTaskId) {
                getDynamicListTaskId = -1;
                LiveParentInfo lpInfo = (LiveParentInfo) data;
                mGuankanshu.setText(lpInfo.getViewCount() + "人");
                guankanNum = lpInfo.getViewCount();
                dynamicList = lpInfo.getDynamicList();
                if (dynamicList != null && dynamicList.size() > 0) {
                    lyAdapter.updateData(dynamicList);
                    lyListView.post(new Runnable() {
                        @Override
                        public void run() {
                            lyListView.smoothScrollToPosition(lyAdapter.getCount() - 1);
                        }
                    });
                    dynamciTime = dynamicList.get(dynamicList.size() - 1).getDynamicTime();
                    PalLog.e("返回的动态时间", dynamciTime);
                }
                audienceList = lpInfo.getAudienceList();
                if (audienceList != null && audienceList.size() > 0) {
                    adapter.clearData();
                    adapter.updateData(audienceList);
                    setValue();
                }
            } else if (taskId == cmtTaskId) {
                PalLog.e("评论成功", "lalala");
                DynamicInfo addInfo = new DynamicInfo();
                addInfo.setCommentContent(cmtText);
                addInfo.setUserName(EatShowApp.getInstance().getmUserInfo().getNickName());
                addInfo.setDynamicType(1);
                addInfo.setUserLevel(EatShowApp.getInstance().getmUserInfo().getUserLevel());
                List<DynamicInfo> dynamicList_self = new ArrayList<DynamicInfo>();
                dynamicList_self.add(addInfo);
                lyAdapter.updateData(dynamicList_self);
                lyListView.post(new Runnable() {
                    @Override
                    public void run() {
                        lyListView.smoothScrollToPosition(lyAdapter.getCount() - 1);
                    }
                });
            } else if (taskId == addFocusTaskId) {
                guanzhuBtn.setVisibility(View.GONE);
                userinfo.setIsFocus(false);
                DynamicInfo guanzhuInfo = new DynamicInfo();
                guanzhuInfo.setDynamicType(6);
                EatShowUserInfo userInfo = EatShowApp.getInstance().getmUserInfo();
                if (userInfo != null) {
                    guanzhuInfo.setUserName(userInfo.getNickName());
                    guanzhuInfo.setUserId(userInfo.getUserId());
                    guanzhuInfo.setUserLevel(userInfo.getUserLevel());
                }
                List<DynamicInfo> dynamicList_self = new ArrayList<DynamicInfo>();
                dynamicList_self.add(guanzhuInfo);
                lyAdapter.updateData(dynamicList_self);
                lyListView.post(new Runnable() {
                    @Override
                    public void run() {
                        lyListView.smoothScrollToPosition(lyAdapter.getCount() - 1);
                    }
                });
            } else if (taskId == songliwuTaskId) {
                if (data != null) {
                    GifInfo info = (GifInfo) data;
                    if (info != null) {
                        jinbiBalance = info.getFlower();
                        jibiTextView.setText(jinbiBalance);
                        String gifId = info.getGiftId();
                        zuodonghua(getEatShowApp().getmUserInfo(), gifId, lianjicount);
                        DynamicInfo slwInfo = new DynamicInfo();
                        slwInfo.setDynamicType(2);
                        slwInfo.setCommentContent(gifId);
                        EatShowUserInfo userInfo = EatShowApp.getInstance().getmUserInfo();
                        if (userInfo != null) {
                            slwInfo.setUserName(userInfo.getNickName());
                            slwInfo.setUserId(userInfo.getUserId());
                            slwInfo.setUserLevel(userInfo.getUserLevel());
                        }
                        List<DynamicInfo> dynamicList_self = new ArrayList<DynamicInfo>();
                        dynamicList_self.add(slwInfo);
                        lyAdapter.updateData(dynamicList_self);
                        lyListView.post(new Runnable() {
                            @Override
                            public void run() {
                                lyListView.smoothScrollToPosition(lyAdapter.getCount() - 1);
                            }
                        });
                    }
                }
            } else if (taskId == goldCoinTaskId) {
                jinbiBalance = (String) data;
                if (isZhuboBalance) {
                    mLivezhuboBalance.setText("花朵数:" + jinbiBalance);
                } else {
                    jibiTextView.setText(jinbiBalance);
                }
            } else if (taskId == doShareTaskId) {
                DynamicInfo addInfo = new DynamicInfo();
                addInfo.setUserName(EatShowApp.getInstance().getmUserInfo().getNickName());
                addInfo.setDynamicType(3);
                addInfo.setUserLevel(EatShowApp.getInstance().getmUserInfo().getUserLevel());
                if (dynamicList == null) {
                    dynamicList = new ArrayList<DynamicInfo>();
                }
                dynamicList.add(0, addInfo);
                lyAdapter.updateData(dynamicList);
                lyListView.post(new Runnable() {
                    @Override
                    public void run() {
                        lyListView.setSelection(lyAdapter.getCount() - 1);
                    }
                });
            }

        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if (taskId == getDynamicListTaskId) {
                getDynamicListTaskId = -1;
            } else if (taskId == songliwuTaskId) {
                if (errorCode == 8006111) {
                    errorDialog = DialogUtil.createDialog(mContext, -1, getString(R.string.prompt), getString(R.string.goldcoin_empty), getString(R.string.ok), getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startActivity(new Intent(mContext, MyFlowerActivity.class));
                        }
                    }, null);
                }
            }
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    }

    ;

    private AlertDialog errorDialog;

    private void doFresh() {
        mHandler.sendEmptyMessageDelayed(111, 2000);
    }

    static class MyHandler extends Handler {
        private SoftReference<PlayerNewActivity> softReference;
        public MyHandler(PlayerNewActivity activity) {
            softReference = new SoftReference<PlayerNewActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            PlayerNewActivity activity = softReference.get();
            if (activity == null) {
                return;
            }
            switch (msg.what) {

                case 111:
                    activity.getDynamicList();
                    activity.mHandler.sendEmptyMessageDelayed(111, 2000);
                    break;
                case 222:
                    activity.doFirstZhibo();
                    break;
                case 333:
                    activity.hideDonghua();
                    break;
                case 444:
                    activity.hiddenView1();
                    break;
                case 555:
                    activity.hiddenView2();
                    break;
                case 666:
                    activity.zanDonghua();
                    activity.mHandler.sendEmptyMessageDelayed(666, 1000);
                    break;
            }
        }
    }

    private ImageView pengyouquan, wenxin, qq, weibo;

    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.share_pop,
                null);
        pengyouquan = ((ImageView) view.findViewById(R.id.share_to_timeline));
        pengyouquan.setOnClickListener(this);
        wenxin = ((ImageView) view.findViewById(R.id.share_to_weixinfriend));
        wenxin.setOnClickListener(this);
        weibo = ((ImageView) view.findViewById(R.id.share_to_weibo));
        weibo.setOnClickListener(this);
        qq = ((ImageView) view.findViewById(R.id.share_to_qq));
        qq.setOnClickListener(this);
        popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
//        mWeiboShareAPI.handleWeiboResponse(intent, this);
    }

    @Override
    public void onResponse(BaseResponse baseResponse) {
        switch (baseResponse.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(this, R.string.weibosdk_toast_share_success,
                        Toast.LENGTH_LONG).show();
                //doShareWeiboGetPoint();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toast.makeText(this, R.string.weibosdk_toast_share_canceled,
                        Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(
                        this,
                        getString(R.string.weibosdk_toast_share_failed)
                                + "Error Message: " + baseResponse.errMsg,
                        Toast.LENGTH_LONG).show();
                break;
        }
    }

    private void doShare() {
        ZhiboActionTask doShareTask = new ZhiboActionTask(mVid, "0");
        doShareTask.addListener(new MyListener(this));
        doShareTaskId = getEatShowApp().getTaskManager().addTask(doShareTask);
    }

    class WeixinShareReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println(intent.getAction());
            weixinuseropenid = intent.getStringExtra(ProtocolConst.WEIXIN_OPENID);

            if (intent.getAction().equalsIgnoreCase(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION)) {
                doShare();
            } else if (intent.getAction().equalsIgnoreCase(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION)) {
                doShare();
            }
            if (mWeixinShareReceive != null) {
                unregisterReceiver(mWeixinShareReceive);
                mWeixinShareReceive = null;
            }
        }

    }

    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {

        }

        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
            doShare();
        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub

        }
    };


    private void shareToWeiXin(String shareUrl, boolean isTimeLine) {
        if (!api.isWXAppSupportAPI() || !api.isWXAppInstalled()) {
            Toast.makeText(mContext, R.string.need_weixin_app, Toast.LENGTH_SHORT).show();
            return;
        }

        if (mWeixinShareReceive != null) {
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }

        if (mWeixinShareReceive == null) {
            mWeixinShareReceive = new WeixinShareReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION);
            registerReceiver(mWeixinShareReceive, filter);
        }
        WXWebpageObject webPage = new WXWebpageObject();
        webPage.webpageUrl = shareUrl;
        WXMediaMessage msg = new WXMediaMessage(webPage);
        //msg.title = ppntitle;
        if (isTimeLine) {
            msg.title = share_title;
        } else {
            msg.title = "第一课堂";
        }
        msg.description = share_title;
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.app_icon);
        weixinshareByte = WeixinShareUtil.bmpToByteArray(bmp, true);
        if (weixinshareByte != null && weixinshareByte.length != 0) {
            msg.thumbData = weixinshareByte;
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline
                : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }

    private void shareToWeiBo(String webpage) {

        if (mWeixinShareReceive != null) {
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }

        if (mWeixinShareReceive == null) {
            mWeixinShareReceive = new WeixinShareReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION);
            registerReceiver(mWeixinShareReceive, filter);
        }

        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();

        if (!TextUtils.isEmpty(webpage)) {
            TextObject textobject = new TextObject();
            textobject.text = "第一课堂";
            weiboMessage.textObject = textobject;
            WebpageObject mediaObject = new WebpageObject();
            mediaObject.identify = Utility.generateGUID();
            mediaObject.defaultText = "第一课堂";
            mediaObject.title = "第一课堂";
            mediaObject.description = share_title;
            mediaObject.actionUrl = webpage;
            if (weiboShareBitmap != null) {
                mediaObject.setThumbImage(weiboShareBitmap);
            } else {
                mediaObject.setThumbImage(BitmapFactory.decodeResource(
                        getResources(), R.drawable.app_icon));
            }
            weiboMessage.mediaObject = mediaObject;
        }

        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;

        // 3. 发送请求消息到微博，唤起微博分享界面
        AuthInfo authInfo = new AuthInfo(this, ProtocolConst.WEIBO_APP_KEY, ProtocolConst.WEIBO_REDIRECT_URL, ProtocolConst.WEIBO_SCOPE);
        Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(getApplicationContext());
        String token = "";
        if (accessToken != null) {
            token = accessToken.getToken();
            weibouserid = accessToken.getUid();
        }
//        mWeiboShareAPI.sendRequest(this, request, authInfo, token, new WeiboAuthListener() {
//
//
//            @Override
//            public void onWeiboException(WeiboException arg0) {
//            }
//
//            @Override
//            public void onComplete(Bundle bundle) {
//                Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
//                AccessTokenKeeper.writeAccessToken(getApplicationContext(), newToken);
//                weibouserid = newToken.getUid();
////                    Toast.makeText(getApplicationContext(), "UID = "+weiboOpenId+"onAuthorizeComplete token = " + newToken.getToken(), 0).show();
//            }
//
//            @Override
//            public void onCancel() {
//            }
//        });


    }

    class MyPagerAdapter extends PagerAdapter {
        public MyPagerAdapter() {
        }

        @Override
        public int getCount() {
            if (mList != null) {
                return mList.size();
            }
            return 0;
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return view == o;
        }


        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            if (mList != null) {
                EatShowUserInfo info = mList.get(position);
                View view = LayoutInflater.from(mContext).inflate(R.layout.viewpager_zhibo, null);
                view.setOnClickListener(PlayerNewActivity.this);
                view.setTag(position);
                ImageView fengmianImage = (ImageView) view.findViewById(R.id.fengmian);
                EVVideoView videoView = (EVVideoView) view.findViewById(R.id.player_surface_view);
                ImageCache.getInstance(mContext).loadBitmapToView(fengmianImage, info.getLiveCoverUrl(), null);
                container.addView(view);
                if (!isViewShow) {
                    mHandler.sendEmptyMessage(222);
                    isViewShow = true;
                }
                return view;
            }

            return super.instantiateItem(container, position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
//            super.destroyItem(container, position, object);
        }
    }

    private boolean isViewShow = false;

    //礼物
    private void hideDonghua() {
        liwuImageView.setVisibility(View.GONE);
        GifDrawable gifFromResource = (GifDrawable) liwuImageView.getDrawable();
        if (gifFromResource != null && !gifFromResource.isRecycled()) {
            gifFromResource.recycle();
        }
    }

    private void hiddenView1() {
        liwuTanKuang.removeView(tankuangView1);
        if (tankuangView2 != null && tankuangView2.getParent() != null) {
            liwuTanKuang.removeView(tankuangView2);
            liwuTanKuang.addView(tankuangView2);
        }
    }

    private void hiddenView2() {
        liwuTanKuang.removeView(tankuangView2);
    }

    private void showView1() {
        if (tankuangView1 != null && tankuangView1.getParent() == null) {
            liwuTanKuang.addView(tankuangView1);
        }
    }

    private void showView2() {
        if (tankuangView2 != null && tankuangView2.getParent() == null) {
            liwuTanKuang.addView(tankuangView2);
        }
    }

    private void songLiwu(GifInfo info) {
        SongLiwuTask task = new SongLiwuTask(mVid, info.getGiftId(), lianjicount);
        task.addListener(new MyListener(this));
        songliwuTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private View tankuangView1, tankuangView2;
    private ImageView headImage1, headImage2, liwuIcon1, liwuIcon2;
    private TextView dengjiText1, dengjiText2, shuliang1, shuliang2, liwuNick1, liwuNick2;
    private long view1time, view2time;
    private ObjectAnimator textScaleAnimation1;
    private ObjectAnimator textScaleAnimation2;
    private AnimatorSet textAnimation;

    private void initAnimation(View view) {
        textScaleAnimation1 = ObjectAnimator.ofFloat(view, View.SCALE_Y, 0.8f, 1.2f, 1f);
//        new ScaleAnimation(1f, 1.2f, 1f, 1.2f,
//                Animation.RELATIVE_TO_SELF, 0.5f,
//                Animation.RELATIVE_TO_SELF, 0.5f);
        textScaleAnimation1.setDuration(500);
        textScaleAnimation1.start();
//        textScaleAnimation2 = new ScaleAnimation(1.2f,1,1.2f,1,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
//        textScaleAnimation2.setDuration(500);
//        textScaleAnimation2.setStartOffset(500);
//        textAnimation = new AnimationSet(false);
//        textAnimation.addAnimation(textScaleAnimation1);
//        textAnimation.addAnimation(textScaleAnimation2);
//        textAnimation.setFillAfter(true);
    }

    private void tankuang(EatShowUserInfo info, String giftId, int count) {
        int liwuId = getResources().getIdentifier("t_" + giftId, "drawable", getPackageName());
        if (tankuangView1 == null) {
            tankuangView1 = LayoutInflater.from(mContext).inflate(R.layout.liwutankuang, liwuTanKuang, false);
            tankuangView1.setBackgroundResource(R.drawable.tankuang);
            headImage1 = (ImageView) tankuangView1.findViewById(R.id.head_img);

            dengjiText1 = (TextView) tankuangView1.findViewById(R.id.dengji);
            liwuNick1 = (TextView) tankuangView1.findViewById(R.id.nickname);
            liwuIcon1 = (ImageView) tankuangView1.findViewById(R.id.liwu_icon);
            shuliang1 = (TextView) tankuangView1.findViewById(R.id.count);
            shuliang1.getPaint().setShadowLayer(1, 2, 2, getResources().getColor(R.color.red));
            tankuangView1.setTag(info.getUserId());
            liwuTanKuang.addView(tankuangView1);
            mHandler.removeMessages(444);
            mHandler.sendEmptyMessageDelayed(444, 3000);
        }

        if (tankuangView2 == null && !info.getUserId().equals(tankuangView1.getTag())) {
            tankuangView2 = LayoutInflater.from(mContext).inflate(R.layout.liwutankuang, liwuTanKuang, false);
            tankuangView2.setBackgroundResource(R.drawable.tankuang);
            headImage2 = (ImageView) tankuangView2.findViewById(R.id.head_img);
            dengjiText2 = (TextView) tankuangView2.findViewById(R.id.dengji);
            liwuIcon2 = (ImageView) tankuangView2.findViewById(R.id.liwu_icon);
            shuliang2 = (TextView) tankuangView2.findViewById(R.id.count);
            shuliang2.getPaint().setShadowLayer(1, 2, 2, getResources().getColor(R.color.red));
            liwuNick2 = (TextView) tankuangView2.findViewById(R.id.nickname);
            tankuangView2.setTag(info.getUserId());
            liwuTanKuang.addView(tankuangView2);
            mHandler.removeMessages(555);
            mHandler.sendEmptyMessageDelayed(555, 3000);
        }

        if (info.getUserId().equals(tankuangView1.getTag())) {
            ImageCache.getInstance(mContext).loadBitmapToView(headImage1, info.getUserLogo(), ViewUtil.getHeadImageSize_40(mContext));
            dengjiText1.setText(info.getUserLevel());
            liwuIcon1.setImageResource(liwuId);
            liwuNick1.setText(URLDecoder.decode(info.getNickName()));
            count++;
            shuliang1.setText(getString(R.string.lianji_count, count));
            initAnimation(shuliang1);
            view1time = System.currentTimeMillis();
            showView1();
            mHandler.removeMessages(444);
            mHandler.sendEmptyMessageDelayed(444, 3000);

        } else if (info.getUserId().equals(tankuangView2.getTag())) {
            count++;
            ImageCache.getInstance(mContext).loadBitmapToView(headImage2, info.getUserLogo(), ViewUtil.getHeadImageSize_40(mContext));
            liwuIcon2.setImageResource(liwuId);
            dengjiText2.setText(info.getUserLevel());
            liwuNick2.setText(URLDecoder.decode(info.getNickName()));
            shuliang2.setText(getString(R.string.lianji_count, count));
            initAnimation(shuliang2);
            view2time = System.currentTimeMillis();
            showView2();
            mHandler.removeMessages(555);
            mHandler.sendEmptyMessageDelayed(555, 3000);
        } else {
            if (view1time > view2time) {
                ImageCache.getInstance(mContext).loadBitmapToView(headImage2, info.getUserLogo(), ViewUtil.getHeadImageSize_40(mContext));
                dengjiText2.setText(info.getUserLevel());
                liwuIcon2.setImageResource(liwuId);
                liwuNick2.setText(URLDecoder.decode(info.getNickName()));
                count++;
                shuliang2.setText(getString(R.string.lianji_count, count));
                initAnimation(shuliang2);
                tankuangView2.setTag(info.getUserId());
                view2time = System.currentTimeMillis();
                showView2();
                mHandler.removeMessages(555);
                mHandler.sendEmptyMessageDelayed(555, 3000);
            } else {
                count++;
                ImageCache.getInstance(mContext).loadBitmapToView(headImage1, info.getUserLogo(), ViewUtil.getHeadImageSize_40(mContext));
                dengjiText1.setText(info.getUserLevel());
                liwuIcon1.setImageResource(liwuId);
                liwuNick1.setText(URLDecoder.decode(info.getNickName()));
                shuliang1.setText(getString(R.string.lianji_count, count));
                initAnimation(shuliang1);
                tankuangView1.setTag(info.getUserId());
                view1time = System.currentTimeMillis();
                showView1();
                mHandler.removeMessages(444);
                mHandler.sendEmptyMessageDelayed(444, 3000);
            }
        }

        if (view1time > view2time) {
            liwuTanKuang.removeView(tankuangView1);
            liwuTanKuang.addView(tankuangView1);
        }

    }

    private GifView.OnStopListener stopListener = new GifView.OnStopListener() {
        @Override
        public void onStop() {
            hideDonghua();
        }
    };

    private void zuodonghua(EatShowUserInfo info, String giftId, int count) {
        tankuang(info, giftId, count);
        int gifUrl = 0;
//        PalLog.e(TAG,giftId);
        if (giftId.equals("0006")) {
            //礼盒
            gifUrl = R.raw.lihegif;

        } else if (giftId.equals("0007")) {
            //奖杯
            gifUrl = R.raw.jiangbei;
        } else if (giftId.equals("0014")) {
            //鲜花
            gifUrl = R.raw.xianhua;
        } else if (giftId.equals("0015")) {
            //笔记本
            gifUrl = R.raw.diannao;
        }
        if (gifUrl != 0) {
            if (liwuImageView.getVisibility() == View.VISIBLE) {
                return;
            }
            liwuImageView.setVisibility(View.VISIBLE);
            try {
                GifDrawable gifFromResource = new GifDrawable(getResources(), gifUrl);
                int frameint = gifFromResource.getDuration();
                liwuImageView.setImageDrawable(gifFromResource);
                mHandler.sendEmptyMessageDelayed(333, frameint);
            } catch (IOException e) {
                e.printStackTrace();
            }
//        if (gifUrl != 0) {
//            if(liwuImageView.getVisibility()==View.VISIBLE){
//                return;
//            }
//            liwuImageView.setVisibility(View.VISIBLE);
//            liwuImageView.setMovieResource(gifUrl);
//            liwuImageView.setOnStopListener(stopListener);
           /* Glide.with(PlayerActivity.this).load(gifUrl).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).listener(new RequestListener<Integer, GifDrawable>() {
                @Override
                public boolean onException(Exception e, Integer integer, Target<GifDrawable> target, boolean b) {
                    return false;
                }

                @Override
                public boolean onResourceReady(GifDrawable gifDrawable, Integer integer, Target<GifDrawable> target, boolean b, boolean b1) {
                    int duration = 0;
                    try {
                        GifDrawable gif = gifDrawable;
                        GifDecoder decoder = gif.getDecoder();
                        for (int i = 0; i < gif.getFrameCount(); i++) {
                            duration += decoder.getDelay(i);
//                            if (i == gif.getFrameCount() - 1) {
//                                PalLog.e(TAG, "gif张数：" + i);
//                            }
                        }
//                        PalLog.e(TAG, "gif时长：" + duration);
                    } catch (Throwable e) {
                    }
                    mHandler.removeMessages(333);
                    mHandler.sendEmptyMessageDelayed(333, duration * 5);
                    return false;
                }
            }).into((Target) new GlideDrawableImageViewTarget(liwuImageView, 1));*/
        }
    }

    private TextView jibiTextView;
    private Button sendGiftBtn;

    private void initLiwuPop() {
//        View view = LayoutInflater.from(mContext).inflate(R.layout.liwu_pop,
//                null);
        liwuLayout = (LinearLayout) findViewById(R.id.liwu_pop);
        jibiTextView = (TextView) findViewById(R.id.jinbi_balance);
        jibiTextView.setOnClickListener(this);
        sendGiftBtn = (Button) findViewById(R.id.send_gift_btn);
        sendGiftBtn.setOnClickListener(this);
        ViewPager viewPager = (ViewPager) findViewById(R.id.liwu_viewpager);
        initPagerView();
        viewPager.setAdapter(new LiwuPagerAdapter(gridViewList));
//        liwuPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
//                ViewGroup.LayoutParams.WRAP_CONTENT);
//        liwuPopWindow.setBackgroundDrawable(new ColorDrawable());
//        liwuPopWindow.setFocusable(true);
//        liwuPopWindow.setOutsideTouchable(true);
    }

    private ArrayList<GridView> gridViewList;
    ArrayList<ArrayList<GifInfo>> liwuList = new ArrayList<ArrayList<GifInfo>>();

    private void getLiwuInfo() {
        ArrayList<GifInfo> liwumidList = new ArrayList<GifInfo>();
        GifInfo info1 = new GifInfo();
        info1.setGiftId("0008");
        info1.setImageId(R.drawable.liwu1);
        info1.setMoney(1);
        liwumidList.add(info1);
        GifInfo info2 = new GifInfo();
        info2.setGiftId("0009");
        info2.setImageId(R.drawable.liwu2);
        info2.setMoney(2);
        liwumidList.add(info2);
        GifInfo info3 = new GifInfo();
        info3.setGiftId("0010");
        info3.setImageId(R.drawable.liwu3);
        info3.setMoney(10);
        liwumidList.add(info3);
        GifInfo info4 = new GifInfo();
        info4.setGiftId("0011");
        info4.setImageId(R.drawable.liwu4);
        info4.setMoney(20);
        liwumidList.add(info4);
        GifInfo info5 = new GifInfo();
        info5.setGiftId("0012");
        info5.setImageId(R.drawable.liwu5);
        info5.setMoney(52);
        liwumidList.add(info5);
        GifInfo info6 = new GifInfo();
        info6.setGiftId("0013");
        info6.setImageId(R.drawable.liwu6);
        info6.setMoney(68);
        liwumidList.add(info6);
        GifInfo info7 = new GifInfo();
        info7.setGiftId("0014");
        info7.setImageId(R.drawable.liwu7);
        info7.setMoney(108);
        liwumidList.add(info7);
        GifInfo info8 = new GifInfo();
        info8.setGiftId("0015");
        info8.setImageId(R.drawable.liwu8);
        info8.setMoney(168);
        liwumidList.add(info8);
        liwuList.add(liwumidList);
        liwumidList = new ArrayList<GifInfo>();
        GifInfo info9 = new GifInfo();
        info9.setGiftId("0001");
        info9.setImageId(R.drawable.liwu9);
        info9.setMoney(1);
        liwumidList.add(info9);
        GifInfo info10 = new GifInfo();
        info10.setGiftId("0002");
        info10.setImageId(R.drawable.liwu10);
        info10.setMoney(2);
        liwumidList.add(info10);
        GifInfo info11 = new GifInfo();
        info11.setGiftId("0003");
        info11.setImageId(R.drawable.liwu11);
        info11.setMoney(10);
        liwumidList.add(info11);
        GifInfo info12 = new GifInfo();
        info12.setGiftId("0004");
        info12.setImageId(R.drawable.liwu12);
        info12.setMoney(52);
        liwumidList.add(info12);
        GifInfo info13 = new GifInfo();
        info13.setGiftId("0005");
        info13.setImageId(R.drawable.liwu13);
        info13.setMoney(66);
        liwumidList.add(info13);
        GifInfo info14 = new GifInfo();
        info14.setGiftId("0006");
        info14.setImageId(R.drawable.liwu14);
        info14.setMoney(108);
        liwumidList.add(info14);
        GifInfo info15 = new GifInfo();
        info15.setGiftId("0007");
        info15.setImageId(R.drawable.liwu15);
        info15.setMoney(168);
        liwumidList.add(info15);
        liwuList.add(liwumidList);
    }

    private ArrayList<GridView> initPagerView() {
        getLiwuInfo();
//        int[][] liwuList = new int[][]{{R.drawable.guzhang,R.drawable.tiantianquan,R.drawable.bangbangtang,R.drawable.ganbei,R.drawable.niupai,R.drawable.lihe,R.drawable.zuanshi,R.drawable.falali},{R.drawable.qiqiu,R.drawable.xiaomogu,R.drawable.bingjiling,R.drawable.memeda,R.drawable.xihuanni,R.drawable.youting,R.drawable.bieshu}};
        gridViewList = new ArrayList<GridView>();
        for (int j = 0; j < 2; j++) {
            final GridView gridView = new GridView(mContext);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            gridView.setLayoutParams(params);
            gridView.setNumColumns(4);
//            gridView.setBackgroundColor(mContext.getResources().getColor(R.color.white_bg));
            gridView.setVerticalSpacing(ViewUtil.dip2px(mContext, 15));
            gridView.setColumnWidth(ViewUtil.dip2px(mContext, 80));
            gridView.setStretchMode(GridView.STRETCH_SPACING);
            final GridAdapter adapter = new GridAdapter();
            gridView.setAdapter(adapter);
            adapter.updateData(liwuList.get(j));

//            gridView.setStretchMode(GridView.STRETCH_SPACING);
            gridViewList.add(gridView);
            final int i = j;
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (i == 0) {
                        ((GridAdapter) (gridViewList.get(1).getAdapter())).setSelectedPosition(-1);
                    } else if (i == 1) {
                        ((GridAdapter) (gridViewList.get(0).getAdapter())).setSelectedPosition(-1);
                    }
                    if (adapter.getSelectPosition() == position) {
                        selectGift = null;
                        adapter.setSelectedPosition(-1);
                    } else {
                        lianjicount = 0;
                        beforeTime = 0;
                        selectGift = (GifInfo) adapter.getItem(position);
                        adapter.setSelectedPosition(position);
                    }

                }
            });
        }

        return gridViewList;

    }

    class GridAdapter extends BaseAdapter {
        ArrayList<GifInfo> list = new ArrayList<GifInfo>();
        private int selectPosition = -1;

        public GridAdapter() {
        }

        public void updateData(ArrayList<GifInfo> arrayList) {
            list = arrayList;
            notifyDataSetChanged();
        }

        public void setSelectedPosition(int i) {
            selectPosition = i;
            notifyDataSetChanged();
        }

        public int getSelectPosition() {
            return selectPosition;
        }

        @Override
        public int getCount() {
            if (list != null && list.size() > 0) {
                return list.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            if (list != null && list.size() > 0) {
                return list.get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
//            PalLog.e(TAG,"list数量："+list.size());
            convertView = LayoutInflater.from(mContext).inflate(R.layout.gift_item, null);
            ImageView imageView = (ImageView) convertView.findViewById(R.id.gift_image);
//            AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(ViewUtil.dip2px(mContext,80),ViewUtil.dip2px(mContext,80));
//            imageView.setLayoutParams(layoutParams);
            GifInfo info = list.get(position);
            imageView.setImageResource(info.getImageId());
            if (selectPosition == position) {
                imageView.setBackgroundResource(R.drawable.gif_select_bg);
            } else {
                imageView.setBackgroundResource(R.drawable.gift_bg);
            }
            return convertView;
        }
    }

    class LiwuPagerAdapter extends PagerAdapter {
        private ArrayList<GridView> views = new ArrayList<GridView>();

        public LiwuPagerAdapter(ArrayList<GridView> l) {
            views = l;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(views.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(views.get(position));
            return views.get(position);
        }

        @Override
        public int getCount() {
            return views.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    @Override
    public void adapterLiwu(EatShowUserInfo info, TextView textView, String giftId, int count, boolean isZx) {
        EatShowUserInfo userInfo = getEatShowApp().getmUserInfo();
        if (!isZx && userInfo != null && !info.getUserId().equals(userInfo.getUserId())) {
            zuodonghua(info, giftId, count);
        }
        String giftName = null;
        if (giftId.equals("0001")) {
            giftName = "气球";
        } else if (giftId.equals("0002")) {
            giftName = "小蘑菇";
        } else if (giftId.equals("0003")) {
            giftName = "冰淇淋";
        } else if (giftId.equals("0004")) {
            giftName = "喜欢你";
        } else if (giftId.equals("0005")) {
            giftName = "手表";
        } else if (giftId.equals("0006")) {
            giftName = "礼盒";
        } else if (giftId.equals("0007")) {
            giftName = "奖杯";
        } else if (giftId.equals("0008")) {
            giftName = "鼓掌";
        } else if (giftId.equals("0009")) {
            giftName = "棒棒糖";
        } else if (giftId.equals("0010")) {
            giftName = "咖啡";
        } else if (giftId.equals("0011")) {
            giftName = "手绘画";
        } else if (giftId.equals("0012")) {
            giftName = "地球仪";
        } else if (giftId.equals("0013")) {
            giftName = "金牌教师";
        } else if (giftId.equals("0014")) {
            giftName = "鲜花";
        } else if (giftId.equals("0015")) {
            giftName = "笔记本";
        }
        textView.setTextColor(getResources().getColor(R.color.orange_public));
        textView.setText("送了一个" + giftName);
    }

    @Override
    public void OnLiveStop() {
        liwuLayout.setVisibility(View.GONE);
        if (errorDialog != null && errorDialog.isShowing()) {
            errorDialog.dismiss();
        }
        Intent overIntent = new Intent(mContext, LiveOverActivity.class);
//        overIntent.putExtra("ZHIBO_LIST",mList);
//        overIntent.putExtra("CURRENT_POSITION",currentPosition);
        overIntent.putExtra("NUM", guankanNum);
        overIntent.putExtra("VID", mVid);
        overIntent.putExtra("liveState", liveState);
        overIntent.putExtra("TITLE", share_title);
        overIntent.putExtra("FROM", 1);
        startActivity(overIntent);
        finish();
        if (null != mEVPlayer) {
//            mEVPlayer.watchStop(Preferences.getInstance(getApplicationContext()).getSessionId(), mVid);
            mEVPlayer.watchStop();

        }
    }

    private String getGiftName(String giftId) {
        String giftName = null;
        if (giftId.equals("0001")) {
            giftName = "气球";
        } else if (giftId.equals("0002")) {
            giftName = "小蘑菇";
        } else if (giftId.equals("0003")) {
            giftName = "冰淇淋";
        } else if (giftId.equals("0004")) {
            giftName = "喜欢你";
        } else if (giftId.equals("0005")) {
            giftName = "手表";
        } else if (giftId.equals("0006")) {
            giftName = "礼盒";
        } else if (giftId.equals("0007")) {
            giftName = "奖杯";
        } else if (giftId.equals("0008")) {
            giftName = "鼓掌";
        } else if (giftId.equals("0009")) {
            giftName = "棒棒糖";
        } else if (giftId.equals("0010")) {
            giftName = "咖啡";
        } else if (giftId.equals("0011")) {
            giftName = "手绘画";
        } else if (giftId.equals("0012")) {
            giftName = "地球仪";
        } else if (giftId.equals("0013")) {
            giftName = "金牌教师";
        } else if (giftId.equals("0014")) {
            giftName = "鲜花";
        } else if (giftId.equals("0015")) {
            giftName = "笔记本";
        }
        return giftName;
    }


    /**
     * 点赞动画
     */

    private int[] colors;

    private void zanDonghua() {
        colors = new int[]{getResources().getColor(R.color.dianzan_color1), getResources().getColor(R.color.dianzan_color2), getResources().getColor(R.color.dianzan_color3), getResources().getColor(R.color.dianzan_color4), getResources().getColor(R.color.dianzan_color5)};
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        params.addRule(RelativeLayout.CENTER_HORIZONTAL);
        final HeartImageView imageView = new HeartImageView(mContext);
        imageView.setColor(colors[new Random().nextInt(colors.length)]);
        imageView.setVisibility(View.INVISIBLE);
        dianzanLayout.addView(imageView, params);
        imageView.post(new Runnable() {
            @Override
            public void run() {
                initDianzanAnimation(imageView);
            }
        });
    }


    private void initDianzanAnimation(final ImageView imageView) {
        ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(imageView, View.SCALE_X, 0.5f, 1f);
        ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(imageView, View.SCALE_Y, 0.5f, 1f);
        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(imageView, View.ALPHA, 0.5f, 1f);
        AnimatorSet enterAnimatorSet = new AnimatorSet();
        enterAnimatorSet.playTogether(scaleXAnimator, scaleYAnimator, alphaAnimator);
        enterAnimatorSet.setDuration(500);
        enterAnimatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                imageView.setVisibility(View.VISIBLE);
            }
        });

        int[] randomArray = {0, 1};
        int point1x = 0;
        int point1y = 0;
        int point2x = 0;
        int point2y = 0;
        int screenWidth = ViewUtil.getScreenWidth(mContext);
        int mid = ViewUtil.dip2px(mContext, 25);
        int left = dianzanLayout.getLeft();
        int width = dianzanLayout.getWidth();
        int height = dianzanLayout.getHeight();
        int top = dianzanLayout.getTop();
        int bottom = dianzanLayout.getBottom();
        if (randomArray[new Random().nextInt(2)] == 0) {
            point1x = new Random().nextInt(width / 2 - mid);//+left;
        } else {
            point1x = width - new Random().nextInt(width / 2 - mid);
        }
        if (randomArray[new Random().nextInt(2)] == 0) {
            point2x = new Random().nextInt(width / 2 - mid);//+left;
        } else {
            point2x = width - new Random().nextInt(width / 2 - mid);
        }
        point1y = height - new Random().nextInt(height / 2 - mid);
        point2y = new Random().nextInt(height / 2 - mid);
        int startX = width / 2 - (imageView.getWidth() / 2);//new Random().nextInt(width)+left;
        int startY = height - imageView.getHeight();
        int endX = new Random().nextInt(width);
        int endY = 0;

        ValueAnimator translateAnimator = ValueAnimator.ofObject(new HeartEvaluator(new PointF(point1x, point1y), new PointF(point2x, point2y)), new PointF(startX, startY), new PointF(endX, endY));
        translateAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                PointF pointF = (PointF) animation.getAnimatedValue();
                imageView.setX(pointF.x);
                imageView.setY(pointF.y);
            }
        });
        translateAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                dianzanLayout.removeView(imageView);
            }
        });
        TimeInterpolator[] timeInterpolator = {new LinearInterpolator(), new AccelerateDecelerateInterpolator(), new DecelerateInterpolator(), new AccelerateInterpolator()};
        translateAnimator.setInterpolator(timeInterpolator[new Random().nextInt(timeInterpolator.length)]);
        ObjectAnimator translateAlphaAnimator = ObjectAnimator.ofFloat(imageView, View.ALPHA, 1f, 0.5f);
        translateAlphaAnimator.setInterpolator(new DecelerateInterpolator());
        AnimatorSet translateAnimatorSet = new AnimatorSet();
        translateAnimatorSet.playTogether(translateAnimator, translateAlphaAnimator);
        translateAnimatorSet.setDuration(3000);
        AnimatorSet allAnimator = new AnimatorSet();
        allAnimator.playSequentially(enterAnimatorSet, translateAnimatorSet);
        allAnimator.start();
    }
}
